package com.jumper.property.comparer.core.convert.impl;

import com.alibaba.fastjson.JSON;
import com.jumper.property.comparer.core.convert.PropertyConverter;
import com.jumper.property.comparer.core.annotations.convert.DateFormat;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.util.Date;
import java.util.TimeZone;

/**
 * 本地时间属性转换器
 */
@Slf4j
public class DatePropertyConverter implements PropertyConverter {

    @Override
    public Object convert(Object propertyValue, Field field) {
        if (propertyValue == null) {
            return null;
        }
        DateFormat dateFormat = field.getAnnotation(DateFormat.class);
        if (dateFormat == null) {
            return propertyValue;
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(dateFormat.pattern());
            sdf.setTimeZone(TimeZone.getTimeZone(ZoneId.of(dateFormat.zoneOffset())));
            return sdf.format(((Date) propertyValue));
        } catch (Exception e) {
            log.warn("Date格式转换异常:{}", JSON.toJSONString(propertyValue), e);
        }
        return propertyValue;
    }
}
